slinding window 可以逐漸取得正確的涵蓋範圍,先用right開始從頭加,加到超過target就開始用left從頭減。
class Solution {
public:
int minOperations(vector<int>& nums, int x) {
int target = 0;
for(int num : nums){
target += num;
}
target -= x;
if(target == 0){
return nums.size();
}
int cur = 0;
int l = 0;
int max_len = 0;
for(int r = 0; r < nums.size(); r++){
cur += nums[r];
while(cur > target && l <= r){
cur -= nums[l];
l++;
}
if(cur == target){
max_len = max(max_len, r - l + 1);
}
}
return max_len ? nums.size() - max_len : -1;
}
};